import React, { useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  AlertCircle,
  Check,
  FileUp,
  Loader2,
  Trash2,
  Upload as UploadIcon,
} from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { UploadFileAPI } from "@/api/uploading";

// 文件上传函数，处理API调用和返回结果
const uploadTemplateFile = async (file) => {
  try {
    // 调用上传接口，传入文件
    const response = await UploadFileAPI.upload(file);
    
    // 检查响应状态
    if (response.code !== 200) {
      throw new Error(response.msg || "文件上传失败");
    }
    
    // 返回数据中的文件信息
    return response.data;
  } catch (error) {
    console.error("文件上传失败:", error);
    throw new Error(error.message || "文件上传失败，请重试");
  }
};

export default function TemplateBasicInfoForm({
  template,
  onSubmit,
  onCancel,
}) {
  const [formData, setFormData] = useState({
    name: template?.name || "",
    code: template?.code || "",
    description: template?.description || "",
    templateType: template?.templateType || "constructionScheme",
    version: template?.version || "1.0",
    // 新增字段存储API返回的完整信息
    fileUrl: template?.wordTemplateUrl || "",
    fileName: template?.wordTemplateFilename || "",
    docId: template?.docId || "",
    docPath: template?.docPath || "",
    docUploadDate: template?.docUploadDate || "",
  });

  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadError, setUploadError] = useState("");
  const fileInputRef = useRef(null);

  const handleChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: null }));
    }
  };

  // 处理文件选择 - 选择后直接上传
  const handleFileSelect = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // 验证Word文件类型
    const isValidFile = validateFile(file);
    if (!isValidFile.valid) {
      setUploadError(isValidFile.message);
      return;
    }

    // 清除之前的上传状态
    resetUploadState();

    // 立即上传文件
    await uploadSelectedFile(file);
  };

  // 验证文件类型和大小
  const validateFile = (file) => {
    const wordFileTypes = [
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .docx
      "application/msword", // .doc
    ];
    const wordExtensions = /(\.docx|\.doc)$/i;
    const maxSize = 10 * 1024 * 1024; // 10MB

    // 验证文件类型
    if (!wordFileTypes.includes(file.type) && !wordExtensions.test(file.name)) {
      return { valid: false, message: "请上传Word格式的文件 (.docx, .doc)" };
    }

    // // 验证文件大小
    // if (file.size > maxSize) {
    //   return { valid: false, message: "文件大小不能超过10MB" };
    // }

    return { valid: true };
  };

  // 上传选中的文件
  const uploadSelectedFile = async (file) => {
    setIsUploading(true);
    setUploadProgress(0);
    setUploadError("");

    try {
      // 调用上传函数
      const result = await uploadTemplateFile(file);
      
      // 根据API返回的实际结构更新formData
      // 从返回结果中提取所需信息
      handleChange("fileUrl", result.docUrl);       // 存储文件URL
      handleChange("fileName", result.docName);     // 存储文件名
      handleChange("docId", result.docId);          // 存储文档ID
      handleChange("docPath", result.docPath);      // 存储文档路径
      handleChange("docUploadDate", result.docUploadDate); // 存储上传日期
      
      // 设置上传进度为100%
      setUploadProgress(100);
    } catch (error) {
      setUploadError(error.message || "文件上传失败，请重试");
      // 重置文件选择
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    } finally {
      setIsUploading(false);
    }
  };

  // 重置上传状态
  const resetUploadState = () => {
    setUploadProgress(0);
    setUploadError("");
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  // 移除已上传文件
  const handleRemoveFile = () => {
    handleChange("fileUrl", "");
    handleChange("fileName", "");
    handleChange("docId", "");
    handleChange("docPath", "");
    handleChange("docUploadDate", "");
    resetUploadState();
  };

  const validate = () => {
    const newErrors = {};

    if (!formData.name || !formData.name.trim()) {
      newErrors.name = "模板名称不能为空";
    }

    if (formData.name && formData.name.length > 100) {
      newErrors.name = "模板名称不能超过100个字符";
    }

    if (formData.description && formData.description.length > 500) {
      newErrors.description = "描述不能超过500个字符";
    }

    if (!formData.templateType) {
      newErrors.templateType = "请选择模板类型";
    }

    if (!formData.version || !formData.version.trim()) {
      newErrors.version = "版本号不能为空";
    }

    // // 验证文件是否已上传
    // if (!formData.fileUrl) {
    //   newErrors.file = "请上传模板文件";
    // }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!validate()) {
      return;
    }

    setIsSubmitting(true);
    try {
      // 准备提交的数据，包含API返回的所有文件信息
      const submitData = {
        ...formData,
        wordTemplateFilename: formData.fileName,
        wordTemplateUrl: formData.fileUrl,
        // 包含其他需要提交的文件信息
        docId: formData.docId,
        docPath: formData.docPath,
        docUploadDate: formData.docUploadDate
      };

      await onSubmit(submitData);
    } catch (error) {
      console.error("提交表单失败:", error);
      setErrors({ submit: error.message || "提交失败，请重试" });
    } finally {
      setIsSubmitting(false);
    }
  };

  // 触发文件选择对话框
  const triggerFileSelect = () => {
    resetUploadState();
    fileInputRef.current?.click();
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4 pt-4">
      <div>
        <Label htmlFor="name">模板名称 *</Label>
        <Input
          id="name"
          value={formData.name}
          onChange={(e) => handleChange("name", e.target.value)}
          placeholder="例如：带电跨越施工方案模板"
          className={errors.name ? "border-red-500" : ""}
        />
        {errors.name && (
          <p className="text-red-500 text-sm mt-1">{errors.name}</p>
        )}
      </div>

      <div>
        <Label htmlFor="description">模板描述</Label>
        <Textarea
          id="description"
          value={formData.description}
          onChange={(e) => handleChange("description", e.target.value)}
          placeholder="简要描述此模板的用途和特点"
          rows={3}
          className={errors.description ? "border-red-500" : ""}
        />
        {errors.description && (
          <p className="text-red-500 text-sm mt-1">{errors.description}</p>
        )}
      </div>

      {/* 上传区域 */}
      <div>
        <Label htmlFor="templateFile">
          上传Word模板文件 *{" "}
          <span className="text-gray-500 text-sm">(仅支持单个文件)</span>
        </Label>
        <div
          className={`mt-1 border-2 rounded-md p-6 text-center transition-colors
          ${
            formData.fileUrl && !isUploading
              ? "border-blue-200 bg-blue-50"
              : "border-dashed border-gray-300 hover:border-blue-300 hover:bg-blue-50"
          }`}
          onClick={
            !isUploading && !formData.fileUrl ? triggerFileSelect : undefined
          }
          style={{
            cursor: !isUploading && !formData.fileUrl ? "pointer" : "default",
          }}
        >
          {!formData.fileUrl ? (
            isUploading ? (
              // 上传中状态
              <>
                <div className="flex items-center justify-center">
                  <Loader2 className="w-5 h-5 text-blue-500 animate-spin mr-2" />
                  <span className="text-sm text-blue-700">正在上传...</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2.5 mt-3">
                  <div
                    className="bg-blue-600 h-2.5 rounded-full transition-all"
                    style={{ width: `${uploadProgress}%` }}
                  ></div>
                </div>
                <p className="text-xs text-gray-500 mt-2">
                  {uploadProgress}% 完成
                </p>
              </>
            ) : (
              // 未上传状态 - 可选择文件
              <>
                <UploadIcon className="w-10 h-10 mx-auto text-gray-400 mb-2" />
                <p className="text-sm text-gray-600 mb-3">
                  拖放单个Word文件到此处，或点击选择文件
                </p>
                <p className="text-xs text-gray-500">
                  仅支持 .docx, .doc 格式，最大10MB，选择后将自动上传
                </p>
                <input
                  ref={fileInputRef}
                  id="templateFile"
                  type="file"
                  multiple={false}
                  accept=".docx,.doc"
                  onChange={handleFileSelect}
                  className="hidden"
                />
              </>
            )
          ) : (
            // 已上传状态
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <div className="flex items-center">
                  <FileUp className="w-5 h-5 text-green-500 mr-2" />
                  <span className="text-sm font-medium truncate max-w-[70%]">
                    {formData.fileName}
                  </span>
                </div>
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="h-8 w-8 p-0 text-gray-500 hover:text-red-500"
                  onClick={handleRemoveFile}
                  disabled={isUploading}
                >
                  <Trash2 className="w-4 h-4" />
                </Button>
              </div>
              <div className="flex items-center justify-center">
                <Check className="w-4 h-4 text-green-500 mr-1" />
                <span className="text-xs text-green-600">上传成功</span>
              </div>
              {/* 显示上传时间 */}
              {formData.docUploadDate && (
                <p className="text-xs text-gray-500">
                  上传时间: {formData.docUploadDate}
                </p>
              )}
            </div>
          )}
        </div>

        {uploadError && (
          <Alert variant="destructive" className="mt-2">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{uploadError}</AlertDescription>
          </Alert>
        )}

        {errors.file && (
          <p className="text-red-500 text-sm mt-1">{errors.file}</p>
        )}
      </div>

      <div className="grid grid-cols-1 gap-4">
        <div>
          <Label htmlFor="version">版本号 *</Label>
          <Input
            id="version"
            value={formData.version}
            onChange={(e) => handleChange("version", e.target.value)}
            placeholder="例如: 1.0"
            className={errors.version ? "border-red-500" : ""}
          />
          {errors.version && (
            <p className="text-red-500 text-sm mt-1">{errors.version}</p>
          )}
        </div>
      </div>

      {errors.submit && (
        <div className="p-3 bg-red-50 border border-red-200 rounded-md">
          <p className="text-red-800 text-sm">{errors.submit}</p>
        </div>
      )}

      <div className="flex justify-end gap-3 pt-4">
        {onCancel && (
          <Button
            type="button"
            variant="outline"
            onClick={onCancel}
            disabled={isSubmitting || isUploading}
          >
            取消
          </Button>
        )}
        <Button
          type="submit"
          className="bg-blue-600 hover:bg-blue-700"
          disabled={isSubmitting || isUploading}
        >
          {isSubmitting
            ? "处理中..."
            : template
            ? "更新信息"
            : "创建并编辑内容"}
        </Button>
      </div>
    </form>
  );
}
    